package com.hanxiaozhang.base.service.impl;

import com.hanxiaozhang.constant.CacheName;
import com.hanxiaozhang.constant.DelFlagEnum;
import com.hanxiaozhang.redis.util.CacheUtil;
import com.hanxiaozhang.security.CurrentUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import com.hanxiaozhang.base.dao.DictDao;
import com.hanxiaozhang.base.entity.DictEntity;
import com.hanxiaozhang.base.service.DictService;
import org.springframework.transaction.annotation.Transactional;


/**
 * 数据字典
 *
 * @author hanxiaozhang
 * @email hanxiaozhang2018@sina.com
 * @date 2021-04-07
 */
@Service
// @CacheConfig：抽取类中的所有@CachePut、@Cacheable、@CacheEvict的公共配置
@CacheConfig(cacheNames = CacheName.DICT_12HOUR)
public class DictServiceImpl implements DictService {

    @Resource
    private DictDao dictDao;
    @Autowired
    private CacheUtil cacheUtil;

    @Override
    public DictEntity get(Long dictId) {
        return dictDao.get(dictId);
    }

    @Override
    public List<DictEntity> list(Map<String, Object> map) {

        return dictDao.list(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "#dict.type")
    public int save(DictEntity dict) {
        dict.setCreateBy(CurrentUserUtil.getUserName())
                .setCreateDate(LocalDateTime.now())
                .setDelFlag(DelFlagEnum.NORMAL.getCode());
        return dictDao.save(dict);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "#dict.type")
    public int update(DictEntity dict) {
        dict.setUpdateBy(CurrentUserUtil.getUserName())
                .setUpdateDate(LocalDateTime.now());
        return dictDao.update(dict);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "#p1")
    public int remove(Long dictId, String type) {

        return dictDao.remove(dictId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchRemove(Long[] dictIds, String[] types) {
        cacheUtil.delDictByTypes(types);
        return dictDao.batchRemove(dictIds);
    }

    @Override
    @Cacheable(key = "#p0", unless = "#result == null")
    public List<DictEntity> listByType(String type) {
        return dictDao.listByType(type);
    }

}
